package com.hakgc.demo.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 基于XML配置的Servlet
 * 在WEB-INF/web.xml中进行注册配置
 * @author Xing.Jiejian
 * @date 2020/11/7
 */
public class MyXmlServlet extends HttpServlet {
    /**
     * 用来处理post请求
     * @param request 基于Http协议的请求对象
     * @param response 给予Http协议的响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("post：username-"+username);
        response.setContentType("text/html;charset=utf-8");
        //直接响应文本信息给用户
        PrintWriter out = response.getWriter();
        out.println("POST响应用户");
    }

    /**
     * 用来处理Get请求
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收用户提交的请求数据
        String username = request.getParameter("username");
        System.out.println("get请求：username-"+username);
        response.sendRedirect("index.html");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String charset = config.getInitParameter("charset");
        System.out.println("获取初始化参数charset："+charset);
    }
}
